package com.nondo.rdp.auth.listener;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.nondo.rdp.auth.common.MessageCoverter;
import com.nondo.rdp.auth.domain.Message;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.event.PushApplicationEvent;
import com.nondo.rdp.auth.service.UserMessageService;
import com.nondo.rdp.auth.service.UserService;
import com.nondo.rdp.core.common.AliyunPushTool;
import com.nondo.rdp.core.model.Notification;

/**
 * 消息推送监听器
 */
@Component
public class PushApplicationListener implements ApplicationListener<PushApplicationEvent> {

	@Autowired
	UserService userService;

	@Autowired
	UserMessageService userMessageService;
	
	@Autowired
	AliyunPushTool aliyunPushTool;

	public void onApplicationEvent(PushApplicationEvent event) {
		System.out.println("接收到事件：" + event.getClass());

		// 消息保存
		saveUserMessage(event);
		// 消息推送
		pushMessage(event);
	}

	/**
	 * 消息保存
	 * 
	 * @param event
	 */
	public void saveUserMessage(PushApplicationEvent event) {
		Message message = event.getMessage();
		this.userMessageService.saveUserMessage(message);
	}

	/**
	 * 消息推送
	 * 
	 * @param event
	 */
	public void pushMessage(PushApplicationEvent event) {
		Message message = event.getMessage();
		Notification notification = MessageCoverter.toNotification(message);
		String uids = message.getUids();
		try {
			if (StringUtils.isBlank(uids)) {
				aliyunPushTool.pushNoticeToAndroid(notification);
				aliyunPushTool.pushNoticeToIOS(notification);
			} else {
				String[] uidArray = uids.split(",");
				for (String uid : uidArray) {
					User user = userService.findOne(Long.parseLong(uid));
					if (StringUtils.isNotBlank(user.getDeviceId()) && !"null".equals(user.getDeviceId())) {
						notification.setDeviceId(user.getDeviceId());
						aliyunPushTool.pushNoticeToAndroid(notification);
						aliyunPushTool.pushNoticeToIOS(notification);
					}
				}
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

}
